const mysql = require('mysql');

// 创建数据库连接
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'your_username',
    password: 'your_password',
    database: 'your_database',
});

// 连接到数据库
connection.connect((err) => {
    if (err) {
        console.error('Error connecting to database: ' + err.stack);
        return;
    }
    console.log('Connected to database as id ' + connection.threadId);
});

// 插入数据
const insertSql = 'INSERT INTO your_table (column1, column2) VALUES (?, ?)';
const insertValues = ['value1', 'value2'];
connection.query(insertSql, insertValues, (error, results, fields) => {
    if (error) throw error;
    console.log('Inserted ' + results.affectedRows + ' row(s)');
});

// 查询数据
connection.query('SELECT * FROM your_table', (error, results, fields) => {
    if (error) throw error;
    console.log('The results are: ', results);
});

// 更新数据
const updateSql = 'UPDATE your_table SET column1 = ? WHERE id = ?';
const updateValues = ['new_value', 1];
connection.query(updateSql, updateValues, (error, results, fields) => {
    if (error) throw error;
    console.log('Updated ' + results.affectedRows + ' row(s)');
});

// 删除数据
const deleteSql = 'DELETE FROM your_table WHERE id = ?';
const deleteId = 1;
connection.query(deleteSql, deleteId, (error, results, fields) => {
    if (error) throw error;
    console.log('Deleted ' + results.affectedRows + ' row(s)');
});

// 关闭连接
connection.end((err) => {
    if (err) {
        console.error('Error closing database connection: ' + err.stack);
        return;
    }
    console.log('Database connection closed');
});
